<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div  class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <div>
          <a-row>
            <a-col style='height: 45px'>
<!--              教师选择器 -->
<!--              <j-select-multi-teacher v-model='queryParam.teacherId'></j-select-multi-teacher>-->
              <a-form-model-item label='年级' prop='queryParam.gradeId'>
                <s-dict-select-tag :type='selectType' @change='changeGradeId' v-model='queryParam.gradeId'
                                   placeholder='请选择年级'
                                   dictCode='cou_grade,grade_name,id,tenant_id  is not null order by  grade_order' />
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
        <div v-if='toggleSearchStatus'>
          <a-row>
            <a-col style='height: 95px'>
              <a-form-model-item label='班级' prop='queryParam.classId'>
                <s-multi-select-tag :type='selectMultiType'
                                    v-model='queryParam.classId' placeholder='请选择班级'
                                    :is-pin-yin='isPinYin'
                                    :dictCode='queryParamSelect.classIdSelect' />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col style='height: 75px'>
              <a-form-model-item label='科目' prop='queryParam.subjectId'>
                <s-dict-select-tag style='overflow-y: scroll;height: 70px' :type='selectType' placeholder='请选择科目' v-model='queryParam.subjectId'
                                   @change='handleSubjectChange'
                                   dictCode='cou_subject,subject_name,id,subject_iz_open =1 and del_flag =0  order by subject_order'></s-dict-select-tag>

              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col style='height: 120px'>
              <a-form-model-item label='教师'>
                <s-multi-select-tag :type='selectMultiType' :options='teacherList' v-model='queryParam.teacherId'
                                    placeholder='请选择教师'>
                </s-multi-select-tag>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col style='height: 45px'>
              <a-form-model-item label='建筑' prop='queryParam.buildingId'>
                <s-dict-select-tag class='a-row-under' style='overflow-y: scroll;height: 35px' :type='selectType' placeholder='请选择建筑' v-model='queryParam.buildingId'
                                   @change='handleBuildingChange'
                                   dictCode='fac_building,building_name,id,building_iz_open =1 order by building_classroom_capatity'></s-dict-select-tag>

              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col>
              <a-form-model-item label='教室'>
                <s-multi-select-tag :type='selectMultiType' :options='classroomList' v-model='queryParam.classroomId'
                                    :is-pin-yin='isPinYin'
                                    placeholder='请选择教室'>
                </s-multi-select-tag>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
        <div>
          <a-row style='margin-top: 30px'>
            <a-col :offset='8'>
            <span>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
              <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='handleAdd' type='primary' icon='plus'>新增</a-button>
      <a-button @click='cellEditFun' type='primary' v-show="this.cellEdidFlag==false" icon='edit'>编辑</a-button>
      <a-button @click='cellEditCancelFun' v-show="this.cellEdidFlag==true" type='primary' icon='cancel'>取消</a-button>
      <a-button @click='cellEditSaveFun' v-show="this.cellEdidFlag==true" type='primary' icon='save'>保存</a-button>
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('rel_class_subject_teacher')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"-->
      <!--                @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal"-->
      <!--                     @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='batchDel'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
      <template>
        <span style="float:right;">
          <a @click="searchQuery()"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <a-button v-print="'#datatable'" ghost type="primary">打印</a-button>

          <a-popover title="自定义列" trigger="click" placement="leftBottom">
            <template slot="content">
              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row>
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                        <a-col :span="2"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a><a-icon type="setting" />自定义列</a>
          </a-popover>
        </span>
      </template>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

<!--      <j-vxe-table-->
<!--        ref='vTable'-->
<!--        bordered-->
<!--        row-number-->
<!--        row-selection-->
<!--        rowKey='id'-->
<!--        class='j-table-force-nowrap'-->
<!--        keep-source-->
<!--        :columns='columns'-->
<!--        :dataSource='dataSource'-->
<!--        :pagination='ipagination'-->
<!--        :linkage-config='linkageConfig'-->
<!--        @pageChange='handlePageChange'-->
<!--        @edit-closed='handleEditClosed'-->
<!--      >-->
<!--      <span slot='action' slot-scope='text, record'>-->
<!--        <h1>asdfasdfasdf</h1>-->
<!--          <a @click='handleEdit(record)'>编辑</a>-->
<!--          <a-divider type='vertical' />-->
<!--          <a-dropdown>-->
<!--            <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>-->
<!--            <a-menu slot='overlay'>-->
<!--              <a-menu-item>-->
<!--                <a @click='handleDetail(record)'>详情</a>-->
<!--              </a-menu-item>-->
<!--              <a-menu-item>-->
<!--                <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>-->
<!--                  <a>删除</a>-->
<!--                </a-popconfirm>-->
<!--              </a-menu-item>-->
<!--            </a-menu>-->
<!--          </a-dropdown>-->
<!--        </span>-->
<!--      </j-vxe-table>-->

<!--      :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'-->
<!--      size='middle'-->
      <a-table
        id="datatable"
        ref='table'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        size='middle'
        :scroll='{x:true}'
        bordered
        rowKey='classsId'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :loading='loading'

        class='j-table-force-nowrap'
        @change='handleTableChange'>


<!--      <j-vxe-table-->
<!--        ref="xTable"-->
<!--        toolbar-->
<!--        row-number-->
<!--        row-selection-->
<!--        drag-sort-->
<!--        keep-source-->
<!--        :height="580"-->
<!--        :loading="loading"-->
<!--        :dataSource="dataSource"-->
<!--        :columns="columns"-->
<!--        style="margin-top: 8px;"-->
<!--        @valueChange="handleTableChange"-->
<!--      >-->
         <span slot='action' slot-scope='text, record'>
              <a @click='handleEdit(record)'>编辑</a>
              <a-divider type='vertical' />
              <a-dropdown>
                <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>
                <a-menu slot='overlay'>
                  <a-menu-item>
                    <a @click='handleDetail(record)'>详情</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
      </a-table>
    </div>

<!--    <rel-class-subject-teacher-modal ref='modalForm' @ok='modalFormOk'></rel-class-subject-teacher-modal>-->
    <tea-teacher-list-modal ref='refTeaTeacherListModal' :dataSourceModal='dataSourceTotalList' ></tea-teacher-list-modal>
  </a-card>
</template>

<script>

import Vue from 'vue'
import {h} from "vue";
import {Tooltip} from "ant-design-vue";
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
// import RelClassSubjectTeacherModal from './modules/RelClassSubjectTeacherModal'
import moment from 'moment'
import { pushIfNotExist, randomNumber, randomUUID } from '@/utils/util'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import JVxeCellMixins from '@/components/jeecg/JVxeTable/mixins/JVxeCellMixins'
import { getAction, putAction,postAction } from '@api/manage'
import { getBuildingDataList, getClassroomList, getSubjectList, queryTeacherListBySubject } from '@api/commonAPI'
import TeaTeacherListModal from '@views/smart_school/teacher/TeaTeacherListModal'
import JSelectMultiTeacher from '@views/smart_school/components/public/JSelectMultiTeacher'

import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
export default {
  name: 'RelClassSubjectTeacherProList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    TeaTeacherListModal,
    JSelectMultiTeacher,
    JSearchSelectTag

    // RelClassSubjectTeacherModal
  },
  data() {
    return {
      loading: false,
      description: 'rel_class_subject_teacher管理页面',
      linkageConfig: [
        // 可配置多个联动
        { requestData: this.loadMenu, key: 'subjectId_dictText' }
      ],
      clickedCellFlag: '',
      editCellTeacherList: {}, //需要修改的老师的列表
      editCellClassroomList: {}, //需要修改的教室的列表
      //编辑中需要变更的记录，通过编辑组件【老师选择器】后，把编辑后的数据放到这个变量editUpdateCellTeacherList里面，然后统一提交
      editUpdateCellTeacherList:[],
      cellEdidFlag: false, //是否允许编辑的标识
      itemCellData: {}, //单元格数据
      searchOptions: {}, //各科目老师信息
      dataSourceTotalList: [],
      // 表头:列表展示的列，初始为空。
      columns: [
        {
          title: '班级',
          align: 'center',
          dataIndex: 'classId_dictText'
          // type: JVXETypes.input  // JVXETypes.selectSearch  下拉搜索
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 160,
          scopedSlots: { customRender: 'action' }
        }
      ],
//       columns：列表展示的列，初始为空。
//       settingColumns：保存勾选的列设置
//       defColumns：定义列表可以展示的列信息
      //列设置:保存勾选的列设置
      settingColumns:[],
//    列定义:定义列表可以展示的列信息
      defColumns: [{
        title: '学年',
        align: 'center',
        dataIndex: 'schoolYearId_dictText'
        // type: JVXETypes.selectMultiple
      },
        {
          title: '学期',
          align: 'center',
          dataIndex: 'semesterId_dictText'
          // type: JVXETypes.selectMultiple
        }],
      url: {
        list: '/rel_class_subject_teacher/relClassSubjectTeacher/listPro',
        saveupdateUrl: '/rel_class_subject_teacher/relClassSubjectTeacher/saveupdateClassSubjectTeacherRel',

        getColumnsListUrl: '/rel_class_subject_teacher/relClassSubjectTeacher/getColumnsList',
        edit: '/rel_class_subject_teacher/relClassSubjectTeacher/edit',
        delete: '/rel_class_subject_teacher/relClassSubjectTeacher/delete',
        deleteBatch: '/rel_class_subject_teacher/relClassSubjectTeacher/deleteBatch',
        exportXlsUrl: '/rel_class_subject_teacher/relClassSubjectTeacher/exportXls',
        importExcelUrl: 'rel_class_subject_teacher/relClassSubjectTeacher/importExcel',
        queryTeacherBySubject: '/rel_teacher_subject/relTeacherSubject/queryTeacherListBySubject',
        queryClassUrl: '/classes/couClass/queryByGradeId'
      },
      superFieldList: [],
      pagination: {},
      teacherList: [],
      classList: [],
      subjectList: [],
      buildingList: [],
      classroomList: [],
      selectType: 'radioButtonNew',
      selectTypeKuang: 'radioButtonNewKuang',
      selectMultiType: 'checkbox',
      isPinYin: false,
      //查询条件联动部分定义
      queryParamSelect: {},
      //
      createElementFum: null,
    }
  },
  created() {
    this.getColumns()
    this.initColumns()  //动态加载列名
    this.getSuperFieldList()
    this.initSearchOptions() //初始化各科老师
    this.getTeacherLists() //初始化所有老师
    //this.initList()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  render: function renderFn (h) {
    this.createElementFum = h
    return this.cellEditRenderFun(this.item)
  },
  // render: this.cellEditRenderFun(createElement) ,
  // render: function (createElement) {
  //   return createElement('div', [
  //     createElement('a-input', {
  //       domProps: {
  //         value: '',
  //       },
  //       ref: 'input',
  //       attrs: {
  //         value: this.value
  //       },
  //       on: {
  //         input: (event) => {
  //           this.$emit('input', event)
  //         },
  //         blur: () => {
  //           this.show = 'text'
  //           this.$emit('refreshTable')
  //         },
  //       },
  //       class: {
  //         showClass: this.show != 'input',
  //       },
  //     }),
  //     createElement('span', {
  //       domProps: {
  //         innerText: this.value
  //       },
  //       on: {
  //         click: () => {
  //           this.show = 'input'
  //           this.$nextTick(() => {
  //             this.$refs.input.focus()
  //           })
  //         }
  //       },
  //       class: {
  //         showClass: this.show != 'text',
  //       },
  //     }),
  //   ])
  //
  // },

  methods: {
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'subjectId', text: '科目id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'teacherId', text: '任课教师id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'classroomId', text: '教室场地id，允许空', dictCode: '' })
      this.superFieldList = fieldList
    },
    handlePageChange(event) {
      // 重新赋值
      this.pagination.current = event.current
      this.pagination.pageSize = event.pageSize
      // 查询数据
      this.loadData()
    },
    changeGradeId() {
      if (this.queryParam.gradeId) { //判断不为空
        this.queryParamSelect.classIdSelect = 'cou_class,class_name,id,class_iz_open  =1 and class_iz_delete  = 0 and grade_code=\'' + this.queryParam.gradeId + '\' order by  class_order'
      }
    },
    handleEditClosed(event) {
      let row = event.row
      console.log(row)
      let params = {
        id: row.id,
        subjectId: row.subjectId_dictText,
        teacherId: row.teacherId_dictText
      }
      // console.log(params)
      putAction(this.url.edit, params).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
        } else {
          this.$message.warning('保存失败')
        }
      })
    },

    async loadMenu(parent) {
      let res
      let list = []
      if (parent === '') {
        res = await getAction('/rel_teacher_subject/relTeacherSubject/querySubject')
        res.result.forEach(item => {
          list.push({
            text: item.subjectName,
            value: item.subjectId
          })
        })
        return list
      } else {
        let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
        let tenantId = localData.value.tenantId
        let param = {
          subjectId: parent,
          tenantId: tenantId
        }
        res = await getAction('/rel_teacher_subject/relTeacherSubject/queryTeacherListBySubject', param)
        res.result.forEach(item => {
          list.push({
            text: item.teacherName,
            value: item.teacherId
          })
        })
        return list
      }
      this.$message.error('级联失败,查找数据为空')
      return list
    },
    async handleSubjectChange() {
      let tenantId = ''
      if (localStorage.length > 0) {
        let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
        tenantId = localData.value.tenantId
        // this.model.tenantId = tenantId
      }
      let params = {
        tenantId: tenantId,
        subjectId: this.queryParam.subjectId
      }
      console.log(params)
      if (this.queryParam.subjectId !== null) {
        let res = await queryTeacherListBySubject(params)
        if (res.success) {
          this.teacherList = []
          res.result.forEach(item => {
            this.teacherList.push({
              value: item.teacherId,
              label: item.teacherName
            })
          })
        }
      }
    },
    async initList() {
      let subjectList = await getSubjectList()
      if (subjectList.code === 200) {
        this.subjectList = []
        subjectList.result.forEach(item => {
          this.subjectList.push({
            label: item.subjectName,
            value: item.subjectId
          })
        })
      }
      // let buildingList = await getBuildingDataList()
      // if (buildingList.code === 200) {
      //   this.buildingList = []
      //   buildingList.result.forEach(item => {
      //     this.buildingList.push({
      //       label: item.buildingName,
      //       value: item.id
      //     })
      //   })
      //
      // }
    },
    async handleBuildingChange() {
      let params = {
        buildingId: this.queryParam.buildingId
      }
      let classroomList = await getClassroomList(params)
      if (classroomList.code === 200) {
        this.classroomList = []
        classroomList.result.forEach(item => {
          this.classroomList.push({
            label: item.classroomName,
            value: item.id
          })
        })

      }
    },
    //列设置更改事件
    onColSettingsChange (checkedValues) {
      var key = this.$route.name+":colsettings";
      console.log("onColSettingsChange:key="+key)
      console.log("onColSettingsChange:checkedValues="+checkedValues+",checkedValues.length="+checkedValues.length)
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter(item => {
        if(item.key =='rowIndex'|| item.dataIndex=='action' || item.showAlwaysFlag /*总是显示showAlwaysFlag=true*/ ){
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns =  cols;
    },
    initColumns(){
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name+":colsettings";
      let colSettings= Vue.ls.get(key);
      if(colSettings==null||colSettings==undefined){
        let allSettingColumns = [];
        this.defColumns.forEach(function (item,i,array ) {
          allSettingColumns.push(item.dataIndex);
        })
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
        // Vue.ls.set(key, allSettingColumns, 7 * 24 * 60 * 60 * 1000)
      }else{
        // this.settingColumns = colSettings;
        // const cols = this.defColumns.filter(item => {
        //   if(item.key =='rowIndex'|| item.dataIndex=='action'){
        //     return true;
        //   }
        //   if (colSettings.includes(item.dataIndex)) {
        //     return true;
        //   }
        //   return false;
        // })
        // this.columns =  cols;
        this.columns = this.getColumns();//重新获取动态列
      }
      this.loading = true;
    },
    //动态查询列
     getColumns(){
      // this.columns
      let settingColumnsList = []
      let defColumsList = [
        // {
        // title: '班级',
        // align: 'center',
        // dataIndex: 'classId_dictText'
        // type: JVXETypes.input // 如果加上了该属性，就代表当前单元格是可编辑的，type就是表单的类型，input就是简单的输入框
        //   key: 'rowIndex',
        //   width: 60,
        //   minWidth: '180px', // 最小宽度，与宽度不同的是，这个不是固定的宽度，如果表格有多余的空间，会平均分配给设置了 minWidth 的列 // 如果要做占满表格的列可以这么写
      // }
      ]
      //从后台查询需要显示的动态列
      let qparam = this.getQueryParams();//查询条件
       getAction(this.url.getColumnsListUrl, {  }).then(res=> {
        if (res.success && res.result) {
          res.result.forEach(item => {
            // let item_colum = item;
            let item_colum;
            // if( item.title != '班级ID' || item.title != '班级') {
              item_colum = {
                title: item.title, dataIndex: item.dataIndex,showAlwaysFlag:item.showAlwaysFlag,showDefaultFlag:item.showDefaultFlag,
                key:  item.dataIndex,
                // type: JVXETypes.normal
                type: JVXETypes.selectSearch,
                width: '180px',
                options: [
                  { title: '马老师', value: '1564436114213761025' },
                  { title: '7-5班级', value: '1564525774604660737' },
                  { title: 'Double', value: 'double' },
                  { title: 'Boolean', value: 'boolean' }
                ],
              }
            // }
            // else{
            //   item_colum = item;
            // }

            //根据换行符换行显示
            item_colum.customRender = (value, row, index) => {
              let that=this;//为了防止this的指向发生改变
              var cellClassId = row['classId']
              var cellSubjectId = item.dataIndex
                var cellkey = item.dataIndex+'_JSON'
                var  cellJSON = row[cellkey] ? row[cellkey] : {classId:cellClassId,subjectId:cellSubjectId,teacherId:null,classroomId:null,teacherName:null,classroomName:null}

              var cellTeacherId = cellJSON ? cellJSON['teacherId'] : "" // record['${cellkey}'] // record[`${item.dataIndex}_JSON`] // [ {cellkey} ]
              var cellTeacherName = cellJSON ? cellJSON['teacherName'] : "" // record['${cellkey}'] // record[`${item.dataIndex}_JSON`] // [ {cellkey} ]
                var cellClassroomName = cellJSON ? cellJSON['classroomName'] : ""
              var cellSelectModeName = item.dataIndex +"."+ cellClassId
              var editCellSelectModeName = 'this.editCellTeacherList.'+cellSelectModeName

              //是否允许换行显示
              var cellText = value && item.allowLineBreaks ?  value.split('\n').map(item2 => { return (<li style='font-weight: bold;'>{item2}</li>) }) : value
              var cellArray = [cellTeacherName && cellTeacherName != null && cellTeacherName != 'null' ? cellTeacherName:<br/>,cellClassroomName && cellClassroomName!=null && cellClassroomName!='null' ? cellClassroomName : <br/>]  //定义需要换行显示的数据内容,如果是空值，则设置换行符号
              //需要显示到单元格中的内容：使用li标签换行显示  //允许换行，且不是固定分组列
              cellText =  !item.fixedGroupColFlag ? cellArray.map( item2 => { return (<li style='font-weight: bold;'>{item2}</li>) } ) : cellText




              //老师选择器：关键组件：想实现老师的修改保存功能
              //函数说明：$createElement(标签名称，{数据参数})
              const selectTeacherCom = this.$createElement(
                'j-select-multi-teacher',
                {
                  value:  cellTeacherId,
                  // 事件on,用来监听input事件
                  on: {
                    //'input': (event)=>{ console.log('input:event');console.log(event);  that.$emit(cellTeacherId,event.target.value) },
                    'change': (event)=>{ that.changeCellTeacherId(cellJSON,event) }   //是不是在这里放上change触发的函数，把变化的值记录到 变量editUpdateCellTeacherList=[]里面
                    //编辑中需要变更的记录，通过编辑组件【老师选择器】后，把编辑后的数据放到这个变量editUpdateCellTeacherList里面，然后统一提交
                  }
                }
              )
              //老师选择器END：关键组件：想实现老师的修改保存功能

              //要返回的Div内容：Div内包含老师选择器
              const obj = {
                // <div class="col-tit"><i class="iconfont icon-tubiao-bingtu"></i>xxxxxxx</div>
                children: this.$createElement(
                  'div',
                  {
                    class: 'col-tit',
                    style: 'width:100%;height:100%;',
                    onclick: () => {this.clickedCellFlag = cellSelectModeName;console.log("被点击了！被点击了！this.clickedCellFlag="+this.clickedCellFlag)},
                    on: {
                      click: () => {
                        // this.handlePieChart(row, index)
                        this.clickedCellFlag = cellSelectModeName
                        //排除无需更新的单元格：如班级无需更新：此处可以考虑从后台设置是否可编辑，在gitColumn的时候，返回允许编辑的选项
                        if(item.dataIndex =='classId' || item.dataIndex =='className') {this.clickedCellFlag = item.dataIndex}
                        console.log("被点击了！被点击了！被点击了！被点击了！this.clickedCellFlag="+this.clickedCellFlag)
                        console.log(row)
                        console.log( this.clickedCellFlag == cellSelectModeName )
                      }
                    },
                  },
                  [
                    this.$createElement(
                      'span',
                      {
                        class: 'iconfont icon-tubiao-bingtu'
                      }
                    ),
                  //需要显示到单元格中的内容：使用li标签换行显示  //允许换行，且不是固定分组列
                     cellText,
                    //增加创建【老师选择器】：如果在编辑状态且被点击，则显示【老师选择器】
                    //编辑状态 允许编辑 且点击了了同名称的单元格
                    this.cellEdidFlag && item.allowEditFlag  && this.clickedCellFlag == cellSelectModeName ? selectTeacherCom : null

                  ]
                ),
                attrs: {},
              };
              if (row.rowSpan > -1) {
                obj.attrs.rowSpan = row.rowSpan;
              }
              return obj;
            };

              // this.cellEditRenderFun(text, record, index)
              // (text, record, index) => {
              //   // console.log(text, record)
              //   // this.createElementFum = Vue.h
              // return this.cellEditRenderFun(Vue.h,text, record, index)
              // }
            //   //   console.log("record="+record)
            //   // console.log(record)
            //   // console.log("index="+index)
            //   // return this.cellSelectFun(text,record, index)
            //   // var cell =  h('a', { href: 'javascript:;' }, text);
            //   var cellText = text ?  text.split('\n').map(item2 => { return (<li style='font-weight: bold;'>{item2}</li>) }) : <span >{text}</span>
            //   var cellkey = item.dataIndex+'_JSON'
            //   var  cellJSON = record[cellkey]
            //   var cellClassId = record['classId']
            //   var cellTeacherName = cellJSON ? cellJSON['teacherName'] : "" // record['${cellkey}'] // record[`${item.dataIndex}_JSON`] // [ {cellkey} ]
            //   var cellClassroomName = cellJSON ? cellJSON['classroomName'] : ""
            //   var cellArray = [cellTeacherName,cellClassroomName]
            //   // var cell = cellTeacherName ?   (<span style='font-weight: bold;' >{cellTeacherName}</span> )   : cellText
            //
            //   cellText = cellJSON ? cellArray.map(item2 => { return (<li style='font-weight: bold;'>{item2}</li>) })  : cellText
            //   // var dataSourceModalList = [{id:cellJSON['teacherId']}]
            //   // var cellbtn =  (<j-select-multi-teacher v-model={ item.dataIndex } dataSourceModal={dataSourceModalList}></j-select-multi-teacher>)
            //   // var cellSelectTeacher = () => {return ( <j-multi-select-tag options={this.teacherList} v-model={ item.dataIndex } placeholder="请选择教师"   style='width: 200px;'>  </j-multi-select-tag> )}
            //   var cellSelectModeName = item.dataIndex +"."+ cellClassId
            //   var cellSelectOptions = this.teacherList.map(item3 => { let va = item3.value; let la = item3.label; return (<option value='{va}'>{la}</option>)})
            //   var cellSelectTeacher = cellJSON && this.cellEdidFlag  ?
            //                          ( <select options={this.teacherList} name={cellSelectModeName} style='width: 200px;'>
            //                            {cellSelectOptions}
            //                          </select> )
            //     : cellText
            //
            //   // var cell = this.cellEdidFlag ?  cellbtn : cellText;
            //
            //   var cell = cellSelectTeacher
            //   // this.$refs.refTeaTeacherListModal.openModal();
            //   console.log("cell="+cell.toString()+"cell.getType()=")
            //   console.log(cell)
            //   return cell
            // }



            // if(item_colum.showDefaultFlag){
            //   //默认显示
            //   settingColumnsList.push(item_colum)
            // }
            //总是显示 或 默认显示 的列
            if(item.showAlwaysFlag || item.showDefaultFlag){
              settingColumnsList.push(item_colum)
            }
            //全部列定义
            defColumsList.push(item_colum)
            // defColumsList.push({
            //   title: item.title,
            //   align: item.align,
            //   dataIndex: item.dataIndex
            // })
          })
          this.defColumns = []
          this.settingColumns = []
          this.defColumns = defColumsList
          this.settingColumns = settingColumnsList
          this.columns = settingColumnsList
          console.log("this.columns="+this.columns+",type=");
          console.log(this.columns);
          // this.$refs["vTable"].columns = this.columns
          // this.ref.columns  = this.columns
          // setTimeout(() => {
          //   // this.$refs["JVxeTable"].columns = this.columns
          //   this.$refs.xTable.columns = settingColumnsList;
          //   this.loading = false
          // }, 1000)

          // var key = this.$route.name+":colsettings";
          // Vue.ls.set(key, settingColumnsList, 7 * 24 * 60 * 60 * 1000)
          // this.initColumns();
          // this.onColSettingsChange(settingColumnsList)
        }
      })
      return defColumsList
    },
    changeCellTeacherId(cellJSON,newTeacherIdValue){
      console.log("changeCellTeacherId:editUpdateCellTeacherList.length="+this.editUpdateCellTeacherList.length)
      console.log("changeCellTeacherId:cellJSON="+cellJSON)
      console.log(cellJSON,newTeacherIdValue)
      //是不是在这里放上change触发的函数，把变化的值记录到 变量editUpdateCellTeacherList=[]里面
      //1.判断是否变化更新了
      //2.判断是否已经在更新列表中，在的话需要更新
      if(newTeacherIdValue && newTeacherIdValue != cellJSON.teacherId) {
        var updatIndex = -1;//false
        for (let i = 0; i < this.editUpdateCellTeacherList.length; i++) {
          if(this.editUpdateCellTeacherList[i]["classId"] == cellJSON.classId && this.editUpdateCellTeacherList[i]["subjectId"] == cellJSON.subjectId ){
            updatIndex = i;//true
            break;
          }
        }
        if(updatIndex >=0){
          // this.editUpdateCellTeacherList[i].teacherIdOld = cellJSON.teacherId;
          this.editUpdateCellTeacherList[updatIndex]["teacherId"] = newTeacherIdValue;
        }else {
          cellJSON.teacherIdOld = cellJSON.teacherId;
          cellJSON.teacherId = newTeacherIdValue;
          this.editUpdateCellTeacherList.push(cellJSON)
        }
      }


      console.log("changeCellTeacherId:editUpdateCellTeacherList.length="+this.editUpdateCellTeacherList.length)
      console.log(this.editUpdateCellTeacherList)


    },
    async getTeacherLists(){
      let getTeacherUrl = "/teacher/teaTeacher/queryTeacherLists"
      getAction(getTeacherUrl).then((res)=>{
        if (res.success) {
          this.teacherList = []
          res.result.forEach(item => {
            this.teacherList.push({
              value: item.id,
              label: item.teacherName
            })
          })
        }
      })
    },
    //初始化各科目下的老师
    async initSearchOptions(){
      let tenantId = ''
      if (localStorage.length > 0) {
        let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
        tenantId = localData.value.tenantId
        // this.model.tenantId = tenantId
      }

      // for (const item of this.columns) {
      //   let subjectId = item.dataIndex
        let params = {
          tenantId: tenantId,
          // subjectId: subjectId
        }
        console.log(params)
        if (params.subjectId !== null && params.subjectId !== 'classId' && params.subjectId !== 'className' && params.subjectId !=='schoolYearId_dictText' && params.subjectId !== 'semesterId_dictText') {
          let res = await queryTeacherListBySubject(params)
          if (res.success) {
            let teacherListBySubjectList = {}

            res.result.forEach(item2 => {
              let teacherListBySubject = teacherListBySubjectList[item2.subjectId] ? teacherListBySubjectList[item2.subjectId] : []
              teacherListBySubject.push({
                value: item2.teacherId,
                label: item2.teacherName
              })
              teacherListBySubjectList[item2.subjectId] = teacherListBySubject

            })

            // from["this.searchOptions."+subjectId] = teacherListBySubject
            console.log("teacherListBySubjectList=")
            console.log(teacherListBySubjectList)
          }
        }

    },
    // cellSelectFun(text,record, index){
    //   console.log("text="+text)
    //   console.log("record="+record)
    //   console.log("index="+index)
    //   console.log(record)
    //   let keyStr;
    //   for (const recordElement of Object.keys(record) ){
    //     if(recordElement.indexOf("_JSON")){
    //       keyStr = recordElement.replace("_JSON","")
    //       break;
    //     }
    //   }
    //   console.log("keyStr="+keyStr)
    //
    //   console.log("index="+index)
    //   console.log(index)
    //   let result;
    //   let asyncFlag = true
    //
    // //   result= (  text ? text.split('\n').map(item2 => {
    // //         // return (<li style='font-weight: bold;'>{item}</li>)
    // //         return this.cellEdidFlag ? (<j-search-select-tag
    // //           placeholder="请选择"
    // //           v-model="this.itemCellData.dataIndex"
    // //           dict="tea_teacher,teacher_name,id"
    // //           async={true}
    // //           // dictOptions={"this.searchOptions."+keyStr}
    // //           >
    // //         </j-search-select-tag>
    // //         ) : (<li>{item2}</li>)
    // //       }) :
    // //       this.cellEdidFlag ? (
    // //         <j-search-select-tag
    // //           placeholder="请选择"
    // //           v-model='eval("this.itemCellData."+keyStr)'
    // // //           dictOptions={"this.searchOptions."+keyStr}
    // //             >
    // // </j-search-select-tag>
    // //         //   ,
    // //         // <tea-teacher-list-modal ref='refTeaTeacherListModal' :dataSourceModal='dataSourceTotalList' ></tea-teacher-list-modal>
    // // ) :
    // //         (<li>{text}</li>)  //加上空值返回，可以显示页面的表格单元格线
    // //   )
    //
    //   //第一个参数（必要参数）：主要是用于提供dom中的html内容，类型可以是字符串、对象或函数。
    //   //第二个参数（对象类型，可选）：用于设置这个dom中的一些样式、属性、传的组件的参数、绑定事件之类的。
    //   //第三个参数（类型是数组，数组元素类型是VNode,可选）：主要用于设置分发的内容，如新增的其他组件。
    //   // result = return createElement('li',{},[]);
    //
    //   return result
    // },

    cellEditRenderFun(createElementFum,text, record, index) {
      console.log('cellEditRenderFun--------------------')
      // console.log(text, record, index)
      // console.log(text, record, index)
      return Vue.h('div')
  // return Vue.h('div', [
  //   Vue.h('a-input', {
  //     domProps: {
  //       value: '',
  //     },
  //     ref: 'input',
  //     attrs: {
  //       value: this.value
  //     },
  //     on: {
  //       input: (event) => {
  //         this.$emit('input', event)
  //       },
  //       blur: () => {
  //         this.show = 'text'
  //         this.$emit('refreshTable')
  //       },
  //     },
  //     class: {
  //       showClass: this.show != 'input',
  //     },
  //   }),
  //   Vue.h('span', {
  //     domProps: {
  //       innerText: this.value
  //     },
  //     on: {
  //       click: () => {
  //         this.show = 'input'
  //         this.$nextTick(() => {
  //           this.$refs.input.focus()
  //         })
  //       }
  //     },
  //     class: {
  //       showClass: this.show != 'text',
  //     },
  //   }),
  // ])

},
    //
    saveupdate(){
      var param={relClassSubjectTeacherList:this.editUpdateCellTeacherList}
      putAction(this.url.saveupdateUrl,param).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    cellEditFun(){
      this.initSearchOptions()
      this.cellEdidFlag = true;
    },
    cellEditCancelFun(){
      console.log("cellEditCancelFun:this.editCellTeacherList=======================================")
      console.log(this.editCellTeacherList)
      this.cellEdidFlag = false;
    },
    cellEditSaveFun(){
      if(this.editUpdateCellTeacherList.length>0){
        console.log('进入保存：需要保存['+this.editUpdateCellTeacherList.length+"]条记录。需要注意学期、学年信息")
        console.log(this.editUpdateCellTeacherList)
        this.saveupdate();//执行保存
      }
      this.cellEdidFlag = false;
      this.searchQuery();
    }

  },
  mounted(){
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>